package cn.tedu.v1.controller;

import cn.tedu.v1.model.PrescriptionSum;
import cn.tedu.v1.model.Prescription;
import cn.tedu.v1.service.IDrugService;
import cn.tedu.v1.service.IPrescriptionService;
import cn.tedu.v1.service.IPrescriptionSumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;
/**
 * <p>
 * 处方 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-07-06
 */
@RestController
@RequestMapping("/portal/prescription")
public class PrescriptionController {
    private List<PrescriptionSum> prescriptionSums;
    private int start;

    @PostMapping("/adddrug")
    public List<PrescriptionSum> addDrugToPerscription(PrescriptionSum prescriptionSum){
        prescriptionSums.add(prescriptionSum);
        return prescriptionSums;
    }

    @GetMapping("/deletedrug")
    public List<PrescriptionSum> deleteDrugFromPerscription(String drugName){
        for(PrescriptionSum p:prescriptionSums){
            if(p.getDrug()==drugName){
                prescriptionSums.remove(p);
            }
            break;
        }
        return prescriptionSums;
    }

    @Autowired
    IPrescriptionService prescriptionService;
    @Autowired
    IPrescriptionSumService prescriptionSumService;
    @Autowired
    IDrugService drugService;

    @GetMapping("/submitPrescription")
    public void submitPrescription(Integer patientId,Integer doctorId,String info){
        int end=0;
        int sumprice=0;
        for(PrescriptionSum p:prescriptionSums){
            sumprice +=drugService.getpriceByName(p.getDrug())*p.getCount();
            prescriptionSumService.submitPrescription(p);
            end=p.getRecordId();
        }
        start++;
        Prescription perscription=new Prescription()
                .setDoctorId(doctorId)
                .setPatientId(patientId)
                .setCreatedTime(LocalDateTime.now())
                .setInfo(info)
                .setEnd(end)
                .setStart(start)
                .setSumprice(sumprice)
                .setPrescriptionSums(prescriptionSums)
                .setSumcount(prescriptionSums.size());
        prescriptionService.submitPrescription(perscription);
        start=end;
        prescriptionSums.clear();
    }

    @GetMapping("/showallprescription")
    List<Prescription> showAllPrescription(){
        return prescriptionService.showAll();
    }

    @GetMapping("/showprescription")
    Prescription showPrescription(Integer id){
        return prescriptionService.showPrescriptionById(id);
    }

    @PostMapping("/pay")
    void pay(Integer prescriptionId){
        prescriptionService.pay(prescriptionId);
    }
}
